package com.tr.syn;

/**
 * @author TRasdzz
 * @since  2021/3/11 12:03
 * @version 1.0
 */
//不安全的取钱
//两个人去银行账户取钱
public class UnSafeBank {
    public static void main(String[] args) {

        //新建账户
        Account myAccount = new Account(10000, "结婚基金");
        Drawing you = new Drawing(myAccount, 5000, "你");
        Drawing yourWife = new Drawing(myAccount, 10000, "你老婆");
        you.start();
        yourWife.start();

    }
}

//账户
class Account {
    int    money;//余额
    String name;//卡名

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

//银行：模拟存款
class Drawing extends Thread {
    Account account;//账户
    int     drawingMoney;//取了多少钱
    int     nowMoney;//现在手里有多少钱

    public Drawing(Account account, int drawingMoney,String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;

    }

    //取钱
    //synchronized默认锁的this.即Drawing
    @Override
    public void run() {

        //锁的对象是变化的量，需要增删改的对象
        synchronized (account) {
            //判断余额是否充足
            if (drawingMoney > account.money) {
                System.out.println(Thread.currentThread().getName() + "取不了，钱不够");
                return;
            }
            //模拟延时 sleep可以放大问题的发生性


            //余额 = 卡余额 - 要取的钱
            account.money = account.money - drawingMoney;
            System.out.println(account.name + "余额为" + account.money);
            nowMoney = nowMoney + drawingMoney;
            System.out.println(this.getName() + "手里的钱" + nowMoney);

        }

    }
}
//结婚基金余额为5000
//你手里的钱5000
//你老婆取不了，钱不够